package com.example.demo1.exception;

import java.util.ArrayList;
import java.util.List;

import com.example.demo1.response.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 系统异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object systemExceptionHandler(Exception e) {
        logger.error("系统错误:" + e);
        return Response.error(ExceptionEnum.SYSTEM_ERROR);
    }

    // 请求 异常处理
    @ExceptionHandler(ToprsException.class)
    @ResponseBody
    public Response toprsExceptionHandler(ToprsException e) {
        logger.error("请求错误:" + e);
        return Response.error(e.getCode(), e.getMessage());
    }

    // valid 处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Response MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        logger.error("方法错误:" + e);

        return handlerArguResponse(e.getBindingResult());
    }

    private Response handlerArguResponse(BindingResult Result) {
        List<String> errorList = new ArrayList<String>();
        if (Result.hasErrors()) {
            for (ObjectError err : Result.getAllErrors()) {
                errorList.add(err.getDefaultMessage());
            }
        }
        return errorList.size() > 0 ? Response.error(10001, errorList.toString()) : Response.error(10001, "参数错误");

    }

}
